<?php

namespace app\admin\controller;

use app\admin\model\Site;
use app\admin\model\SiteNode;
use app\admin\model\Photo;
use think\Request;

class Sites
{
    public function index()
    {

        $sites = Site::with('siteNode,photos')->select();
//        return $sites;
        return view('Sites/index', compact('sites'));
    }

    /***加载新增页面
     * @return \think\response\View
     */
    public function create()
    {
        $sitenodes = SiteNode::all();
//        return $sitenodes;
        return view('Sites/create', compact('sitenodes'));
    }


    /***保存新增页面
     * @param Request $request
     * @return \think\response\Redirect
     */
    public function save(Request $request)
    {
//        return $request->param();

//        $photo = Photo::create(['image' => $request->param('image')]);
//        $param = $request->param();
//        $param['photo_id'] = $photo->id;
//        Site::create($param);

        Site::create($request->param());

        return redirect('Sites/index');

    }

    /***加载编辑页面
     * @param $id
     * @return \think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function edit($id)
    {
        $sitenodes = SiteNode::all();
        $site = Site::with('siteNode,photos')->find($id);
        return view('Sites/edit', compact('sitenodes', 'site'));
    }

    /***编辑保存
     * @param Request $request
     * @param $id
     * @return \think\response\Redirect
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function update(Request $request, $id)
    {
        $site = Site::find($id);
        $site->allowField(true)->save($request->param(), ['id' => $id]);
        return redirect('Sites/index');
    }

    /***删除
     * @param $id
     * @return \think\response\Redirect
     */
    public function delete($id)
    {
        Site::destroy($id);
        return redirect('Sites/index');
    }
}